<template>
  <div class="admin">
    <div class="main">
      <div>
        <a-space>
          <h2>系统管理</h2>
          <a-button type="primary" @click="showModal1" > 添加资讯 </a-button>
          <a-button type="primary"  @click="showModal"> 添加管理员 </a-button>
        </a-space>
        <div>
          <a-modal v-model="visible" title="添加管理员" @ok="handleOk">
            <a-upload
                name="icon"
                list-type="picture-card"
                class="avatar-uploader"
                style="margin-left: 100px;"
                :show-upload-list="false"
                action="api/v1/icons"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <img width="100%" v-if="imageUrl" :src="imageUrl" alt="icon" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    上传个人头像
                  </div>
                </div>
            </a-upload>
            <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" >
              <a-form-item label='邮箱' >
                <a-input
                  v-decorator="['email', { rules: [{ required: true, message: '请输入邮箱!' }] }]"
                  placeholder="邮箱"
                />
              </a-form-item>
              <a-form-item label='姓名' >
                <a-input
                  v-decorator="['name', { rules: [{ required: true, message: '请输入姓名!' }] }]"
                  placeholder="姓名"
                />
              </a-form-item>
              <a-form-item label='密码' >
                <a-input-password
                  v-decorator="['password', { rules: [{ required: true, message: '请输入密码!' }] }]"
                  placeholder="密码"
                ></a-input-password>
              </a-form-item>
              <a-form-item label='来源' >
                <a-input
                  v-decorator="['from', { rules: [{ required: true, message: '请输入来源!' }] }]"
                  placeholder="班级"
                ></a-input>
              </a-form-item>
              <a-form-item label='手机号' >
                <a-input
                  v-decorator="['phone', { rules: [{ required: true, message: '请输入邮箱!' }] }]"
                  placeholder="手机号"
                />
              </a-form-item>
              <a-form-item label='职位' >
                <a-input
                  v-decorator="['position', { rules: [{ required: true, message: '请输入职位!' }] }]"
                  placeholder="职位"
                ></a-input>
              </a-form-item>
              <a-form-item name="sex" label="性别">
                <a-radio-group v-model="sex">
                  <a-radio value="1">男</a-radio>
                  <a-radio value="2">女</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-form>
          </a-modal>
          <a-modal v-model="visible1" title="添加资讯" @ok="handleOk1">
            <a-form :form="form1" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" >
              <a-form-item label='标题' >
                <a-input
                  v-decorator="['title', { rules: [{ required: true, message: '请输入标题!' }] }]"
                  placeholder="标题"
                />
              </a-form-item>
              <a-form-item label='内容' >
                <a-textarea
                  v-decorator="['content', { rules: [{ required: true, message: '请输入内容!' }] }]"
                  placeholder="内容"
                />
              </a-form-item>
            </a-form>
          </a-modal>
        </div>
      </div>
      <div class="content">
        <a-tabs default-active-key="1">
          <a-tab-pane key="1" tab="用户">
            <a-table  :pagination="pagination" @change="fanye" :columns="columns1" :data-source="users" rowKey="id">
              <span slot="role" slot-scope="role">
                {{ROLE[role]}}
              </span>
              <span slot="sex" slot-scope="sex">
                {{sex === 'man'? "男" : "女"}}
              </span>
              <template slot="operation" slot-scope="text, record">
                <a-space>
                  <a-popconfirm
                    v-if="users.length"
                    title="确定要删除?"
                    @confirm="() => userDelete(record)"
                  >
                    <a href="javascript:;" style="color: red ">删除用户</a>
                  </a-popconfirm>
                </a-space>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="资讯管理">
            <a-table :pagination="pagination2" @change="fanye2"  :columns="columns2" :data-source="newsList" rowKey="id">
              <template slot="operation" slot-scope="text, record">
                <a-space>
                  <a-popconfirm
                    v-if="newsList.length"
                    title="确定要删除?"
                    @confirm="() => newsDelete(record)"
                  >
                    <a href="javascript:;" style="color: red ">删除资讯</a>
                  </a-popconfirm>
                  <a-popconfirm
                    v-if="newsList.length"
                    title="确定要关闭?"
                    @confirm="() => newsClose(record)"
                  >
                    <a href="javascript:;" >关闭资讯</a>
                  </a-popconfirm>
                  <a-popconfirm
                    v-if="newsList.length"
                    title="确定通过审批？"
                    @confirm="() => newsApprove(record)"
                  >
                    <a href="javascript:;" >资讯审批</a>
                  </a-popconfirm>
                    <a href="javascript:;" @click="toDetail(record.id)">查看详情</a>
                </a-space>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="3" tab="企业管理">
            <a-table :pagination="pagination3" @change="fanye3"  :columns="columns3" :data-source="comps" rowKey="id">
              <template slot="operation" slot-scope="text, record">
                <a-space>
                  <a-popconfirm
                    v-if="comps.length"
                    title="确定要关闭企业?"
                    @confirm="() => compClose(record)"
                  >
                    <a href="javascript:;" style="color: red ">关闭企业</a>
                  </a-popconfirm>
                   <a-popconfirm
                    v-if="comps.length"
                    title="确定企业通过审批?"
                    @confirm="() => compApprove(record)"
                  >
                     <a href="javascript:;">企业审批</a>
                  </a-popconfirm>
                  
                </a-space>
              </template>
              <span slot="State" slot-scope="State">
                {{COMPSTATE[State]}}
              </span>
              <span slot="PeopleNum" slot-scope="PeopleNum">
                {{COMPPEOPLEMAP[PeopleNum]}}
              </span>
              <span slot="CompType" slot-scope="CompType">
                {{COMPTYPEMAP[CompType]}}
              </span>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="4" tab="职位管理">
             <a-table :pagination="pagination4" @change="fanye4"  :columns="columns4" :data-source="jobs" rowKey="id">
              <span slot="state" slot-scope="state">
                {{JOBSTATE[state]}}
              </span>
              <template slot="operation" slot-scope="text, record">
                <a-space>
                  <a-popconfirm
                    v-if="jobs.length"
                    title="确定要关闭职位?"
                    @confirm="() => jobClose(record)"
                  >
                    <a href="javascript:;" style="color: red" >关闭职位</a>
                  </a-popconfirm>
                  <a-popconfirm
                    v-if="jobs.length"
                    title="确定职位通过审批？?"
                    @confirm="() => jobApprove(record)"
                  >
                    <a href="javascript:;">审批职位</a>
                  </a-popconfirm>
                </a-space>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>
<script>
import "./styles.less";

const columns1 = [
  { title: "邮箱", dataIndex: "email", key: "1" },
  { title: "用户名", dataIndex: "name", key: "2" },
  { title: "来源", dataIndex: "from", key: "6" },
  { title: "角色", dataIndex: "role",  scopedSlots: { customRender: "role" }},
  { title: "性别", dataIndex: "sex", scopedSlots: { customRender: "sex" }},
  { title: "电话", dataIndex: "phone"},
  { title: "操作", key: "operation", scopedSlots: { customRender: "operation" }},
];

const columns2 = [
  { title: "标题", dataIndex: "title", key: "1" },
  { title: "作者", dataIndex: "username", key: "2" },
  { title: "更新时间", dataIndex: "UpdatedAt", key: "3" },
  { title: "状态",  dataIndex:"state",key: "4"},
 { title: "操作", key: "operation", scopedSlots: { customRender: "operation" }},
];

const columns3 = [
  { title: "公司名称", dataIndex: "CompName", key: "1" },
  { title: "城市", dataIndex: "City", key: "2" },
  { title: "公司类型", dataIndex: "CompType", scopedSlots: { customRender: "CompType" }},
  { title: "公司规模", dataIndex: "PeopleNum", scopedSlots: { customRender: "PeopleNum" }},
  { title: "公司状态", dataIndex: "State", scopedSlots: { customRender: "State" }},
  { title: "操作", key: "operation", scopedSlots: { customRender: "operation" }},
];

const columns4 = [
  { title: "职位名称", dataIndex: "jobName", key: "1" },
  { title: "工作地点", dataIndex: "city", key: "2" },
  { title: "招聘数量", dataIndex: "jobNum", key: "6" },
  { title: "薪资区间", dataIndex: "wageSection", key: "3" },
  // { title:""},
  { title: "职位状态", dataIndex:"state",scopedSlots: { customRender: "state" }},
  { title: "操作", key: "operation", scopedSlots: { customRender: "operation" }},
];
import jobAPI from "../../services/job";
import userAPI from "../../services/user";
import newsAPI from "../../services/news";
import compAPI from "../../services/comp";
import { requestWrapper } from "../../utils/request";
import { ROLE, JOBSTATE, COMPSTATE, COMPPEOPLEMAP, COMPTYPEMAP } from '../../const/const';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  data() {
    return {
      columns1,
      columns2,
      columns3,
      columns4,
      JOBSTATE,
      COMPSTATE,
      COMPPEOPLEMAP,
      COMPTYPEMAP,
      ROLE,
      jobs: [],
      users: [],
      comps: [],
      total: 0,
      pageSize: 0,
      page: 0,
      visible: false,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      form1: this.$form.createForm(this, { name: 'coordinated1' }),
      activeKey: 'admin',
      sex: '1',
      loading: false,
      imageUrl: '',
      visible1: false ,
      newsList: [],
      pagination: {pageSize:10, page: 1, total: 0},
      pagination2: {pageSize:10, page: 1, total: 0},
      pagination3: {pageSize:10, page: 1, total: 0},
      pagination4: {pageSize:10, page: 1, total: 0},
    };
  },
  methods: {
    getNewsList(params) {
      requestWrapper( newsAPI.getAllNewsList.bind(null, params), {
      }).then((res) => {
        this.newsList = res.list,
        this.pagination2.pageSize = res.pageSize;
        this.pagination2.page = res.page;
        this.pagination2.total = res.total;
      })
    },
    newsDelete(record){
      requestWrapper(newsAPI.newsDelete.bind(null,record.id),{
        formatDataFn: (res) => res,
          autoSuccess: true,
          successMessage: '删除成功！',
      }).then((res) => {
        this.getNewsList()
      })
    },
    newsApprove(record){
      requestWrapper(newsAPI.newsApprove.bind(null,record.id),{
          formatDataFn: (res) => res,
            autoSuccess: true,
            successMessage: '审批成功！',
        }).then((res) => {
          this.getNewsList()
        })
    },
    newsClose(record){
      requestWrapper(newsAPI.newsClose.bind(null,record.id),{
        formatDataFn: (res) => res,
          autoSuccess: true,
          successMessage: '关闭成功！',
      }).then((res) => {
        this.getNewsList()
      })
    },
    userDelete(record) {
      requestWrapper(userAPI.deleteUser.bind(null,record.id), {
         formatDataFn: (res) => res,
          autoSuccess: true,
          successMessage: '删除成功！',
      }).then((res) => {
        this.getUser()
      });
    },
    compClose(record) {
      requestWrapper(compAPI.compClose.bind(null,record.id), {
         formatDataFn: (res) => res,
          autoSuccess: true,
          successMessage: '关闭成功！',
      }).then((res) => {
        this.getComp()
      }); 
    },
    compApprove(record) {
      requestWrapper(compAPI.compApprove.bind(null,record.id), {
         formatDataFn: (res) => res,
          autoSuccess: true,
          successMessage: '审批通过！',
      }).then((res) => {
        this.getComp()
      }); 
    },
    jobApprove(record) {
      console.log(record.id)
      requestWrapper(jobAPI.jobApprove.bind(null,record.id), {
         formatDataFn: (res) => res,
          autoSuccess: true,
          successMessage: '审批通过！',
      }).then((res) => {
        this.getJobs()
      }); 
    },
    jobClose(record) {
      console.log(record.id);
      requestWrapper(jobAPI.jobClose.bind(null,record.id), {
         formatDataFn: (res) => res,
          autoSuccess: true,
          successMessage: '关闭成功！',
      }).then((res) => {
        this.getJobs()
      }); 
    },
    getJobs(params) {
      requestWrapper(jobAPI.jobsAdmin.bind(null, params), {
        formatDataFn: (res) => res,
      }).then((res) => {
        console.log(res);
        this.jobs = res.result.list;
        this.pagination4.pageSize = res.result.pageSize;
        this.pagination4.page = res.result.page;
        this.pagination4.total = res.result.total;
      });
    },
    getUser(params) {
      requestWrapper(userAPI.getUsers.bind(null, params), {
        formatDataFn: (res) => res,
      }).then((res) => {
        console.log(res);
        this.users=res.result.list;
        this.pagination.pageSize = res.result.pageSize;
        this.pagination.page = res.result.page;
        this.pagination.total = res.result.total;
      });
    },
    getComp(params) {
      requestWrapper(compAPI.compsAdmin.bind(null,params), {
        formatDataFn: (res) => res,
      }).then((res) => {
        console.log(res);
        this.comps=res.result.list
        this.pagination3.pageSize = res.result.pageSize;
        this.pagination3.page = res.result.page;
        this.pagination3.total = res.result.total;
      });
    },
    toDetail(id, e) {
      const detail = this.$router.resolve({
        path: '/news_detail',
        query: {
          newsId: id
        }
      })
      window.open(detail.href,'_blank')
    },
    showModal() {
      this.visible = true;
    },
    showModal1() {
      this.visible1 = true;
    },
    handleOk(e) {
      this.handleSubmit(e);
      this.visible = false;
    },
    handleOk1(e) {
      this.handleSubmit1(e);
      this.visible1 = false;
    },
    handleSubmit1(e) {
      e.preventDefault();
      this.form1.validateFields((err, values) => {
        if (!err) {
          console.log(values);
          requestWrapper( newsAPI.createNew.bind(null, values), {
              autoSuccess: true,
              successMessage: '添加成功！',
          }).then((res) => {
            this.getNewsList()
          })
        }
      });
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          values.role = this.activeKey
          values.sex = this.sex
          values.headImg = this.imageUrl || 'api/v1/icons?path=icons/de/50/de50d524261b5079146bd43d2d382a87.jpg'
          console.log(values);
          requestWrapper( userAPI.regist.bind(null, values), {
              autoSuccess: true,
              successMessage: '添加成功！',
          }).then((res) => {

          })
        }
      });
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = info.file.response.result.urlPath;
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
    fanye(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.getUser({
        pageSize: pagination.pageSize,
        page: pagination.current,
      });
    },
    fanye2(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.getNewsList({
        pageSize: pagination.pageSize,
        page: pagination.current,
      });
    },
    fanye3(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.getComp({
        pageSize: pagination.pageSize,
        page: pagination.current,
      });
    },
    fanye4(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.getJobs({
        pageSize: pagination.pageSize,
        page: pagination.current,
      });
    },
  },
  mounted() {
    this.getJobs();
    this.getUser();
    this.getComp();
    this.getNewsList();
  },
};
</script>
